<?php
// TODO: 不要なようなら後で削除
putenv("NLS_LANG=Japanese_Japan.JA16SJIS");

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

// Ensure library/ is on include_path
$paths = array();
$paths[] = realpath(dirname(APPLICATION_PATH) . DIRECTORY_SEPARATOR . 'library');
$paths[] = realpath(dirname(APPLICATION_PATH) . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'Smarty');
set_include_path(implode(PATH_SEPARATOR, $paths));

require_once 'Zend/Log.php';
require_once 'Zend/Log/Writer/Stream.php';
require_once 'Zend/Log/Filter/Priority.php';
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Plugin/ErrorHandler.php';
require_once 'Zend/Application.php';
require_once 'Smarty.class.php';

__log_debug_ex('+++++++++++++++++++++++++ index start ++++++++++++++++++++++++++');

//デフォルトコントローラ変更
__default_controller_setting();

// 共通エラーハンドリング
__set_error();

// CMS連携URL対応
__set_cmsapi_url($_SERVER['REQUEST_URI']);

// 疑似静的URL対応
require_once('Apm' . DIRECTORY_SEPARATOR . 'Bukkenurl.inc.php');
__set_url($_SERVER['REQUEST_URI'],$_SERVER['REQUEST_METHOD']);

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$application->bootstrap()->run();
__log_debug_ex('+++++++++++++++++++++++++ index end ++++++++++++++++++++++++++');

// 共通エラーハンドリング
function __set_error()
{
    $front = Zend_Controller_Front::getInstance();
    $front->registerPlugin(new Zend_Controller_Plugin_ErrorHandler(
        array('module' => 'error','controller' => 'error','action' => 'error')));
}

// CMSAPI
$__is_cmsapi = false;
$__cmsapi_module = '';
$__cmsapi_controller = '';
$__cmsapi_action = '';
function __set_cmsapi_url($url)
{
    global $__is_cmsapi;
    global $__cmsapi_module;
    global $__cmsapi_controller;
    global $__cmsapi_action;

    if (!ereg('/asn/1/(.*)', $url)){
        return;
    }
    $__is_cmsapi = true;

    $tmp = array();
    $tmp = explode('?', $url);
    $url = array_shift($tmp);

    $tmp = array();
    $tmp = explode('/', $url);
    array_shift($tmp);
    array_shift($tmp);
    array_shift($tmp);
    $api_name = array_shift($tmp);

//__log_error(__FILE__, __LINE__, __METHOD__, $api_name);

    switch ($api_name){
        case 'shop':
            // 加盟店サイト用 2011/08/26
            if (!empty($tmp[0]) && $tmp[0] == 'shoppage') {
                $__cmsapi_module     = 'shop';
                $__cmsapi_controller = 'shoppage';
                $__cmsapi_action     = 'index';
            } else {
                $__cmsapi_module     = 'shop';
                $__cmsapi_controller = 'shopdtl';
                $__cmsapi_action     = 'index';
            }
            break;
        case 'auth':
            $__cmsapi_module     = 'login';
            $__cmsapi_controller = 'login';
            $__cmsapi_action     = 'login';
            break;
        case 'logout':
            $__cmsapi_module     = 'login';
            $__cmsapi_controller = 'login';
            $__cmsapi_action     = 'logout';
            break;
        case 'zenkokucnt':
            $__cmsapi_module     = 'cmsapi';
            $__cmsapi_controller = 'bukkencount';
            $__cmsapi_action     = 'zenkokucnt';
            break;
        case 'sienjutakucnt':
            $__cmsapi_module     = 'cmsapi';
            $__cmsapi_controller = 'bukkencount';
            $__cmsapi_action     = 'sienjutakucnt';
            break;
// 2010.12.17 加盟店向けページ対応 ---->
        case 'bukkeninfo':
            $__cmsapi_module     = 'cmsapi';
            $__cmsapi_controller = 'kameiten';
            $__cmsapi_action     = 'bukkeninfo';
            break;
        case 'shopinfo':
            $__cmsapi_module     = 'cmsapi';
            $__cmsapi_controller = 'kameiten';
            $__cmsapi_action     = 'shopinfo';
            break;
// 2010.12.17 加盟店向けページ対応 ----<
// 2011.07.25 CMS用ログイン情報取得API ---->
        case 'logininfo':
            $__cmsapi_module     = 'cmsapi';
            $__cmsapi_controller = 'mypage';
            $__cmsapi_action     = 'logininfo';
            break;
// 2011.07.25 CMS用ログイン情報取得API ----<
// 2013.02.05 TOP新着物件API ---->
        case 'shinchakutop':
            $__cmsapi_module     = 'cmsapi';
            $__cmsapi_controller = 'shinchaku';
            $__cmsapi_action     = 'top';
            break;
// 2013.02.05 TOP新着物件API ----<
        case 'contents':
        default:
            $__cmsapi_module     = array_shift($tmp);
            $__cmsapi_controller = (!empty($tmp[0])) ? array_shift($tmp) : 'index';
            $__cmsapi_action     = (!empty($tmp[0])) ? array_shift($tmp) : 'index';
            //URL変換対応
            if($__cmsapi_controller == 'tenpo_oem_jump'){
                $__cmsapi_controller = 'tenpo-oem-jump';
            }
//__log_error(__FILE__, __LINE__, __METHOD__, $__cmsapi_module);
//__log_error(__FILE__, __LINE__, __METHOD__, $__cmsapi_controller);
//__log_error(__FILE__, __LINE__, __METHOD__, $__cmsapi_action);
            break;
    }
__log_debug_ex($__cmsapi_module);
__log_debug_ex($__cmsapi_controller);
__log_debug_ex($__cmsapi_action);

    $front = Zend_Controller_Front::getInstance();
    $router = $front->getRouter();
    $route = new Zend_Controller_Router_Route(
        '*',
        array(
            'module'     => $__cmsapi_module,
            'controller' => $__cmsapi_controller,
            'action'     => $__cmsapi_action,
        )
    );
    $router->addRoute('cmsapi', $route);
}
function __is_cmsapi()
{
    global $__is_cmsapi;
    return $__is_cmsapi;
}
function __get_cmsapi_module()
{
    global $__cmsapi_module;
    return $__cmsapi_module;
}
function __get_cmsapi_controller()
{
    global $__cmsapi_controller;
    return $__cmsapi_controller;
}
function __get_cmsapi_action()
{
    global $__cmsapi_action;
    return $__cmsapi_action;
}

// View、Smarty関連の関数
function __get_apm_view_object()
{
    $view = new Zend_View_Smarty(
        __get_module_dir(),
        array(
            'compile_dir' => __get_smarty_templates_c_dir(),
            'config_dir'  => __get_smarty_configs_dir(),
            'cache_dir'   => __get_smarty_cache_dir()
        )
    );
    return $view;
}
function __get_apm_smarty_object()
{
    //__log_debug(__FILE__, __LINE__, __METHOD__, '---------->>>');

    $smarty = new Smarty();
    $configObject = Zend_Registry::get('config');
    $config = $configObject->apm->toArray();
    $smarty->template_dir   = __get_module_dir();
    $smarty->compile_dir    = __get_smarty_templates_c_dir();

    // 2015/02/18 必要ないのでコメントアウト
    // 以下のように指定しても、/library/Zend/View/Smarty.phpで強制的に上書きを行っていたため、
    // 効果はなし。/library/Zend/View/Smarty.phpからは削除。
//    $smarty->register_prefilter('__convert_encoding_to_euc_jp');
//    $smarty->register_postfilter('__convert_encoding_to_sjis');
    $smarty->assign('apm', $config);

    //__log_debug(__FILE__, __LINE__, __METHOD__, '----------<<<');
    return $smarty;
}
function __convert_encoding_to_euc_jp($template_source, &$_smarty)
{
    __log_debug(__FILE__, __LINE__, __METHOD__, '---------->>>');
    __log_debug(__FILE__, __LINE__, __METHOD__, '----------<<<');
    return mb_convert_encoding($template_source, "EUC-JP", "UTF-8");
}
function __convert_encoding_to_sjis($template_source, &$_smarty)
{
    //__log_debug(__FILE__, __LINE__, __METHOD__, '---------->>>');
    //__log_debug(__FILE__, __LINE__, __METHOD__, '----------<<<');
    return mb_convert_encoding($template_source, "UTF-8", "EUC-JP");
}

// パス関連の関数
function __get_tmp_dir()
{
    return dirname(APPLICATION_PATH) . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR;
}
function __get_configs_dir()
{
    return APPLICATION_PATH . DIRECTORY_SEPARATOR . 'configs';
}
function __get_module_dir()
{
    return APPLICATION_PATH . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR;
}
function __get_smarty_templates_c_dir()
{
    return __get_tmp_dir() . DIRECTORY_SEPARATOR . 'templates_c';
}
function __get_smarty_configs_dir()
{
    return __get_tmp_dir() . DIRECTORY_SEPARATOR . 'configs';
}
function __get_smarty_cache_dir()
{
    return __get_tmp_dir() . DIRECTORY_SEPARATOR . 'cache';
}

// 規約に則ったテンプレートパス作成
function __get_default_template_file_path($module, $controller)
{
    $template_file_path = '';
    $template_file_path .= APPLICATION_PATH;
    $template_file_path .= DIRECTORY_SEPARATOR;
    $template_file_path .= 'modules';
    $template_file_path .= DIRECTORY_SEPARATOR;
    $template_file_path .= $module;
    $template_file_path .= DIRECTORY_SEPARATOR;
    $template_file_path .= 'views';
    $template_file_path .= DIRECTORY_SEPARATOR;
    $template_file_path .= 'scripts';
    $template_file_path .= DIRECTORY_SEPARATOR;
    $template_file_path .= $controller;
    $template_file_path .= '.tpl';
    return $template_file_path;
}

//デフォルトコントローラー変更
function __default_controller_setting()
{
    $front = Zend_Controller_Front::getInstance();
    $front->setControllerDirectory(
        array(
            'default' => APPLICATION_PATH.'/modules/test/controllers',
        )
    );
}

// アプリケーションログ出力用の関数
function __log_error($file, $line, $method, $log)
{
    $log = sprintf('%s: %d: %s: %s', $file, $line, $method, $log);
    __log($log, Zend_Log::ERR);
}
function __log_error_array($file, $line, $method, $array)
{
    ob_start();
    print_r($array);
    $buf = ob_get_contents();
    ob_end_clean();
    $log = sprintf('%s: %d: %s: %s', $file, $line, $method, $buf);
    __log($log, Zend_Log::ERR);
}
function __log_debug($file, $line, $method, $log)
{
    $log = sprintf('%s: %d: %s: %s', $file, $line, $method, $log);
    __log($log, Zend_Log::DEBUG);
}
function __log_debug_array($file, $line, $method, $array)
{
    ob_start();
    print_r($array);
    $buf = ob_get_contents();
    ob_end_clean();
    $log = sprintf('%s: %d: %s: %s', $file, $line, $method, $buf);
    __log($log, Zend_Log::DEBUG);
}
function __log_debug_ex($val)
{
    $date = date('Y-m-d');
    $time = __get_microtime();
    if (is_array($val)) {
        ob_start();
        print_r($val);
        $buf = ob_get_contents();
        ob_end_clean();
    } else {
        $buf = $val;
    }
    $log = sprintf("\n __log_debug_ex %s %s %s", $date, $time[1], $buf);
    __log($log, Zend_Log::DEBUG, 'ex');
}
function __log_deprecated_method($file, $line, $method)
{
    $log = sprintf('%s: %d: %s: !!! deprecated method !!!', $file, $line, $method);
    __log($log, Zend_Log::DEBUG);
}
function __log($log, $mode, $file='')
{
    $log_file = '';
    $log_file .= dirname(dirname(__FILE__));
    $log_file .= DIRECTORY_SEPARATOR;
    $log_file .= 'temp';
    $log_file .= DIRECTORY_SEPARATOR;
    $log_file .= 'logs';
    $log_file .= DIRECTORY_SEPARATOR;
    if ($file) {
        $log_file .= date("Ymd").'_'.$file.'_app.log';
    } else {
        $log_file .= date("Ymd").'_app.log';
    }
    $logger = new Zend_Log();
    $writer = new Zend_Log_Writer_Stream($log_file);

    // 以下の2行をコメントアウトするとDEBUGログも出力される
    //$filter = new Zend_Log_Filter_Priority(Zend_Log::ERR);
    //$writer->addFilter($filter);

    $logger->addWriter($writer);
    $logger->log($_COOKIE['apm'].': '.$log, $mode);
}
function __log_request_headers()
{
    $headers  = getallheaders();
    __log_debug(__FILE__, __LINE__, __METHOD__, '#################### REQUEST HEADERS #################### >>>');
    __log_debug_array(__FILE__, __LINE__, __METHOD__, $headers);
    __log_debug(__FILE__, __LINE__, __METHOD__, '#################### REQUEST HEADERS #################### <<<');
}
function __log_response_headers()
{
    $headers  = apache_response_headers();
    __log_debug(__FILE__, __LINE__, __METHOD__, '#################### RESPONSE HEADERS #################### >>>');

    __log_debug_array(__FILE__, __LINE__, __METHOD__, $headers);
    __log_debug(__FILE__, __LINE__, __METHOD__, '#################### RESPONSE HEADERS #################### <<<');
}

// 実行速度計測
$__benchmark_start = array();
$__benchmark_end = array();

$__benchmark_ex_start = array();
$__benchmark_ex_end = array();

function __benchmark_start()
{
    global $__benchmark_start;
    $__benchmark_start = __get_microtime();
}
function __benchmark_end()
{
    global $__benchmark_end;
    $__benchmark_end = __get_microtime();
}
function __get_microtime()
{
    $time = explode(' ',microtime());
    return $time;
}
function __get_benchmark()
{
    global $__benchmark_start;
    global $__benchmark_end;
    $diff=((float)$__benchmark_end[0]+(float)$__benchmark_end[1])-((float)$__benchmark_start[0]+(float)$__benchmark_start[1]);
    return $diff;
}

function __benchmark_ex_start()
{
    global $__benchmark_ex_start;
    $__benchmark_ex_start = __get_microtime();
}
function __benchmark_ex_end()
{
    global $__benchmark_ex_end;
    $__benchmark_ex_end = __get_microtime();
}
function __get_benchmark_ex()
{
    global $__benchmark_ex_start;
    global $__benchmark_ex_end;
    $diff=((float)$__benchmark_ex_end[0]+(float)$__benchmark_ex_end[1])-((float)$__benchmark_ex_start[0]+(float)$__benchmark_ex_start[1]);
    return $diff;
}
function __var_dump($v)
{
  ob_start();
  var_dump($v);
  $r=ob_get_contents();
  ob_end_clean();
  return $r;
}

function __adebug($data) {
  __log(__var_dump($data), Zend_Log::DEBUG, $file='adebug');
}
function __bdebug($data) {
  __log(__var_dump($data), Zend_Log::DEBUG, $file='bdebug');
}


?>
